package com.phpxiu.app.kkylive;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import com.facebook.common.executors.CallerThreadExecutor;
import com.facebook.common.references.CloseableReference;
import com.facebook.datasource.DataSource;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.core.ImagePipeline;
import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber;
import com.facebook.imagepipeline.image.CloseableImage;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.phpxiu.app.utils.KKYUtil;
import com.sina.weibo.sdk.api.ImageObject;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.BaseResponse;
import com.sina.weibo.sdk.api.share.IWeiboHandler;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.constant.WBConstants;
import com.sina.weibo.sdk.exception.WeiboException;


/**
 * @file
 * @brief  新浪微博授权、分享回调界面。
 * @author 吴金洲
 * @note 新浪微博授权、分享回调界面。
 *
 */
public class WBShareActivity extends Activity implements IWeiboHandler.Response {
    public final static String TAG="WBShareActivity";
    public final static String TITLE="title";
    public final static String IMAGE="image";
    public final static String URL="target_url";
    public static IWeiboShareAPI mSinaShareAPI = null;
    private String title;
    private String shareImageUrl="http://pic13.nipic.com/20110415/1369025_121513630398_2.jpg";
    private ImagePipeline mPipeline = Fresco.getImagePipeline();
    private ImageRequest mImageRequest =null;
    private DataSource<CloseableReference<CloseableImage>> bitmapSource;
    private String targetUrl;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(mSinaShareAPI==null){
            mSinaShareAPI= KKYApp.getInstance().mSinaShareAPI;
        }
        if (savedInstanceState != null) {
            mSinaShareAPI.handleWeiboResponse(getIntent(), this);
        }
        title=getIntent().getStringExtra(TITLE);
        shareImageUrl= getIntent().getStringExtra(IMAGE);
        targetUrl=getIntent().getStringExtra(URL);
        preSendMsg();
    }

    /**
     * @see {@link android.app.Activity#onNewIntent}
     */
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // 从当前应用唤起微博并进行分享后，返回到当前应用时，需要在此处调用该函数
        // 来接收微博客户端返回的数据；执行成功，返回 true，并调用
        // {@link IWeiboHandler.Response#onResponse}；失败返回 false，不调用上述回调
        mSinaShareAPI.handleWeiboResponse(intent, this);
    }

    @Override
    public void onResponse(BaseResponse baseResp) {
        if(baseResp!= null){
            switch (baseResp.errCode) {
                case WBConstants.ErrorCode.ERR_OK:
                    if(KKYUtil.DEBUG){
                        Toast.makeText(this, "新浪分享成功!",Toast.LENGTH_LONG).show();
                    }
                    break;
                case WBConstants.ErrorCode.ERR_CANCEL:
                    if(KKYUtil.DEBUG) {
                        Toast.makeText(this, "新浪分享取消!", Toast.LENGTH_LONG).show();
                    }
                    break;
                case WBConstants.ErrorCode.ERR_FAIL:
                    if(KKYUtil.DEBUG) {
                        Toast.makeText(this, "新浪分享失败!",Toast.LENGTH_LONG).show();
                    }
                    break;
            }
        }
        finish();
    }

    /**
     * 预载分享内容
     */
    public void preSendMsg(){
        mImageRequest= ImageRequestBuilder.newBuilderWithSource(Uri.parse(shareImageUrl)).setProgressiveRenderingEnabled(true).build();
        bitmapSource=mPipeline.fetchDecodedImage(mImageRequest,this);
        bitmapSource.subscribe(subscriber, CallerThreadExecutor.getInstance());
    }


    /**
     * Share
     */
    public void shareContent(Bitmap pic){
        if (mSinaShareAPI.isWeiboAppSupportAPI()) {
            int supportApi = mSinaShareAPI.getWeiboAppSupportAPI();
            /*ApiUtils.BUILD_INT_VER_2_2*/
            if (supportApi >= 10351 ) {
                //多条信息发送，实现图文分享
                sendMsg(pic);
            }
        } else {
            //KKYUtil.tip(this,"新浪分享失败示安装微博app或版本不支持！",Gravity.BOTTOM).show();
        }
    }

    private void sendMsg(Bitmap pic){
        // 1. 初始化微博的分享消息
        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
        TextObject textObject = new TextObject();
        textObject.text =String.format(getString(R.string.share_link_summary),title,targetUrl);;
        weiboMessage.textObject=textObject;
        ImageObject imageObject = new ImageObject();
        imageObject.setImageObject(pic);
        weiboMessage.imageObject=imageObject;
        // 2. 初始化从第三方到微博的消息请求
        SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
        // 用transaction唯一标识一个请求
        request.transaction = String.valueOf(System.currentTimeMillis());
        request.multiMessage = weiboMessage;
        mSinaShareAPI.sendRequest(WBShareActivity.this, request);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode==765){
            finish();
        }
    }

    private BaseBitmapDataSubscriber subscriber=new BaseBitmapDataSubscriber() {
        @Override
        public void onNewResultImpl(@Nullable Bitmap bitmap) {
            // You can use the bitmap in only limited ways
            // No need to do any cleanup.
            Log.i(TAG,"分享图片加载成功，准备分享...");
            //设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。
            shareContent(Bitmap.createScaledBitmap(bitmap, 120, 120, true));
        }

        @Override
        public void onFailureImpl(DataSource dataSource) {
            // No cleanup required here.
        }
    };
}
